<?php

/**
 * SMS 短信发送接口
 * Date: 2019/03/04
 */

namespace Lib\Paas;

use Lib\Base\Validate;

class SMS extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 发送短信
     *
     * @param int $msgId 消息模板ID
     * @param string $phone 手机号
     * @param array $replaceData 需要动态填充到模板中的信息，key=模板标记字符串，value=需要填充的值
     * @return bool true-发送成功，false-发送失败
     *
     */
    public function sendMessage($msgId, $phone, $replaceData)
    {
        if (!Validate::checkMobile($phone)) {
            recordLog('接收短信的手机号错误，phone=' . var_export($phone, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        if (!Validate::checkNaturalNum($msgId)) {
            recordLog('短信模板ID错误，msgId=' . var_export($msgId, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        if (isset($replaceData['verifyCode']) && $replaceData['verifyCode'] != '' && !preg_match('/^[0-9a-zA-Z]{4,10}$/', $replaceData['verifyCode'])) {
            recordLog('短信验证码错误，verifyCode=' . var_export($replaceData['verifyCode'], true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        $msgData = [
            'phone' => $phone,
            'messageKey' => $msgId,
        ];

        $msgData = \array_merge($msgData, $replaceData);

        recordLog('发送短信接口请求数据, data=' . var_export($msgData, true), __FILE__, __LINE__);

        //组合URL
        $url = $this->getPaasRequestUrl('resource.sms', $msgData);
        $res = $this->http->get($url);
        recordLog('发送短信接口返回值, data=' . var_export($res, true), __FILE__, __LINE__);
        if ($res['ret'] != '0') {
            $this->tglogReport('框架请求ULink-Paas出现异常，curl_errno：' . $res['ret'] . '，curl_error：' . $res['msg'], 'resource.sms');
            return false;
        }
        $res = $res['data'];

        //success
        if ($res['ret'] == '0' && $res['data']['ret'] == '0') {
            return true;
        } else {
            return false;
        }
    }
}
